﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using System.Threading.Tasks;

namespace NetCoreCMS.Web.Areas.Admin.Controllers
{
    public class ManageController : AreasController
    {
        protected internal Sysconfig sysConfig;
        public const string EDIT_RESULT_VIEW = "~/Areas/Admin/Views/Shared/EditResult.cshtml";
        public IWebHostEnvironment _env { get; set; }
        public IManagerService _manager { get; set; }
        public IManager_logService _manager_log { get; set; }
        public IManager_roleService _manager_role { get; set; }
        public ActionExecutingContext _context { get; set; }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            this._context = context;
            sysConfig = Common.XMLConfig.Sysconfig.loadConfig(_env.ContentRootPath);
            ViewData["config"] = sysConfig;
            base.OnActionExecuting(context);
            if (!IsAdminLogin())
            {
                context.Result = Redirect("/Admin/Login/Index");
                return;
            }
        }
        #region 管理员
        public bool IsAdminLogin()
        {
            //如果Session为Null
            if (HttpContext.Session.Get(CMSKeys.SESSION_ADMIN_INFO) != null)
            {
                return true;
            }
            else
            {
                //检查Cookies
                string adminname = HttpContext.Request.Cookies["AdminName"];
                string adminpwd = HttpContext.Request.Cookies["AdminPwd"];
                if (!string.IsNullOrEmpty(adminname) && !string.IsNullOrEmpty(adminpwd))
                {
                    var model = _manager.GetModel(adminname, adminpwd);
                    if (model != null)
                    {
                        HttpContext.Session.Set(CMSKeys.SESSION_ADMIN_INFO, ByteConvertHelper.Object2Bytes(model));
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 取得管理员信息
        /// </summary>
        public Manager GetAdminInfo()
        {
            if (IsAdminLogin())
            {
                var model = ByteConvertHelper.Bytes2Object<Manager>(HttpContext.Session.Get(CMSKeys.SESSION_ADMIN_INFO));
                if (model != null)
                {
                    return model;
                }
            }
            return null;
        }

        /// <summary>
        /// 检查管理员权限
        /// </summary>
        /// <param name="nav_name">菜单名称</param>
        /// <param name="action_type">操作类型</param>
        public void ChkAdminLevel(string nav_name, string action_type)
        {
            bool result = false;
            var model = GetAdminInfo();
            if (model != null)
            {                
                result = _manager_role.Exists(model.role_id, nav_name, action_type);
            }
            if (!result)
            {
                string msgbox = "parent.jsdialog(\"错误提示\", \"您没有管理该页面的权限，请勿非法进入！\", \"back\")";
                string error = "<script type=\"text/javascript\">" + msgbox + "</script>";
                _context.Result = Content(error, "text/html");
                return;
            }
        }

        /// <summary>
        /// 写入管理日志
        /// </summary>
        /// <param name="action_type"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public async Task<bool> AddAdminLog(string action_type, string remark)
        {
            //写入登录日志
            if (sysConfig.logstatus > 0)
            {
                var model = GetAdminInfo();
                await _manager_log.AddAsync(model.id, model.user_name, action_type, remark, CMSRequest.GetClientUserIp(HttpContext));
                return true;
            }
            return false;
        }

        #endregion
        #region JS提示============================================
        /// <summary>
        /// 添加编辑删除提示
        /// </summary>
        /// <param name="msgtitle">提示文字</param>
        /// <param name="url">返回地址</param>
        public string JscriptMsg(string msgtitle, string url)
        {
            string msbox = "parent.jsprint(\"" + msgtitle + "\", \"" + url + "\")";
            ViewBag.ClientScript = msbox;
            return msbox;
        }
        /// <summary>
        /// 带回传函数的添加编辑删除提示
        /// </summary>
        /// <param name="msgtitle">提示文字</param>
        /// <param name="url">返回地址</param>
        /// <param name="callback">JS回调函数</param>
        public string JscriptMsg(string msgtitle, string url, string callback)
        {
            string msbox = "parent.jsprint(\"" + msgtitle + "\", \"" + url + "\", " + callback + ")";
            ViewBag.ClientScript = msbox;
            return msbox;
        }
        #endregion
    }
}